/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package util;

import beans.Mail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import rn.MailRN;

/**
 *
 * @author Caio
 */
public class Utilidades {
        
    //método para compactar arquivo em memoria
    public static byte[] zipBytes(byte[] input) throws IOException {
        String filename = "fatura.pdf";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        ZipEntry entry = new ZipEntry(filename);
        entry.setSize(input.length);
        zos.putNextEntry(entry);
        zos.write(input);
        zos.closeEntry();
        zos.close();
        return baos.toByteArray();
    }
    
    //método para descompactar arquivo em memoria
    public static  byte[] unzipBytes(byte[] input) throws IOException {
       ByteArrayInputStream bais = new ByteArrayInputStream(input);
       ZipInputStream zis = new ZipInputStream(bais);
       ZipEntry entry = null;
       
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       while ((entry = zis.getNextEntry())!= null) {
           baos = new ByteArrayOutputStream();
           int data = 0;
           while ((data = zis.read())!= -1) {
               baos.write(data);
           }
           baos.close();
       }
       
       zis.close();
       bais.close();
       return baos.toByteArray();
    }
    
    public static Boolean enviarEmailCadastro(String destinatario, Integer id) throws EmailException{
        try {
            //capturando url
            HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            StringBuffer html = request.getRequestURL();
            String url = html.toString();
            url = url.replace("cadastro", "ativacao");
            String link_ativacao = "\n\nLink de ativação: "+url+"?id="+id;
            
            MailRN rnmail = new MailRN();
            Mail mail = rnmail.listar().get(0);
            //
            Email commonsEmail = new SimpleEmail(); 
            commonsEmail.setHostName(mail.getSmtp());
            commonsEmail.setSmtpPort(mail.getPorta());
            commonsEmail.setAuthenticator(new DefaultAuthenticator(mail.getUsuario(), mail.getSenha()));
            commonsEmail.setSSLOnConnect(mail.getSsl());
            commonsEmail.setFrom(mail.getEmail());
            commonsEmail.setSubject(mail.getTitulo());
            commonsEmail.setMsg(mail.getMensagem()+link_ativacao);
            commonsEmail.addTo(destinatario);
            commonsEmail.send();
            return true;
        } catch (EmailException e) {
            return false;
        }
    }
    
    public static Boolean enviarEmailFatura(String destinatario, String hash) throws EmailException{
        try {
            //capturando url
            HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            StringBuffer html = request.getRequestURL();
            String url = html.toString();
            url = url.replace("financeiro_fatura", "financeiro_fatura_externa");
            
            String mensagem = "\n\nLink para gerar sua fatura:\n"+url+"?md5="+hash;
            
            MailRN rnmail = new MailRN();
            Mail mail = rnmail.listar().get(0);
            //
            Email commonsEmail = new SimpleEmail(); 
            commonsEmail.setHostName(mail.getSmtp());
            commonsEmail.setSmtpPort(mail.getPorta());
            commonsEmail.setAuthenticator(new DefaultAuthenticator(mail.getUsuario(), mail.getSenha()));
            commonsEmail.setSSLOnConnect(mail.getSsl());
            commonsEmail.setFrom(mail.getEmail());
            commonsEmail.setSubject("CNPOSTO - NOVA FATURA DISPONÍVEL");
            commonsEmail.setMsg(mensagem);
            commonsEmail.addTo(destinatario);
            commonsEmail.send();
            return true;
        } catch (EmailException e) {
            return false;
        }
    }
    
    public static String capturarIP() {
        HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();

        String ip = request.getHeader("X-Real-IP");
        if (null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip)) {
            // get first ip from proxy ip
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }
    
    public static boolean isCPF(String CPF) {
        // considera-se erro CPF's formados por uma sequencia de numeros iguais
        if (CPF.equals("00000000000") || CPF.equals("11111111111") ||
            CPF.equals("22222222222") || CPF.equals("33333333333") ||
            CPF.equals("44444444444") || CPF.equals("55555555555") ||
            CPF.equals("66666666666") || CPF.equals("77777777777") ||
            CPF.equals("88888888888") || CPF.equals("99999999999") ||
           (CPF.length() != 11))
           return(false);

        char dig10, dig11;
        int sm, i, r, num, peso;

        // "try" - protege o codigo para eventuais erros de conversao de tipo (int)
        try {
            // Calculo do 1o. Digito Verificador
            sm = 0;
            peso = 10;
            for (i=0; i<9; i++) {              
                // converte o i-esimo caractere do CPF em um numero:
                // por exemplo, transforma o caractere '0' no inteiro 0         
                // (48 eh a posicao de '0' na tabela ASCII)         
                num = (int)(CPF.charAt(i) - 48); 
                sm = sm + (num * peso);
                peso = peso - 1;
            }

            r = 11 - (sm % 11);
            if ((r == 10) || (r == 11))
                 dig10 = '0';
            else dig10 = (char)(r + 48); // converte no respectivo caractere numerico

            // Calculo do 2o. Digito Verificador
            sm = 0;
            peso = 11;
            for(i=0; i<10; i++) {
                num = (int)(CPF.charAt(i) - 48);
                sm = sm + (num * peso);
                peso = peso - 1;
            }

            r = 11 - (sm % 11);
            if ((r == 10) || (r == 11))
                dig11 = '0';
            else dig11 = (char)(r + 48);

        // Verifica se os digitos calculados conferem com os digitos informados.
            if ((dig10 == CPF.charAt(9)) && (dig11 == CPF.charAt(10)))
                return(true);
            else 
                return(false);
        } catch (InputMismatchException erro) {
            return(false);
        }
    }
    
}
